import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken,
  removeToken
} from '@/utils/auth' // get token from cookie

import getPageTitle from '@/utils/get-page-title'
import {
  userDeptList
} from "@/api/login";

import service from "@/utils/request";

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/shared2', '/sharedVideo'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  // 初始化接口地址
  let baseUrl = document.URL.split('/').slice(0, 3).join('/') + '/api'
  //
  console.log('baseUrl', baseUrl);
  if (baseUrl.includes('http://localhost') || baseUrl.includes('http://192.168.10.136')) {
    baseUrl = 'http://192.168.10.71:8999/api' // 线上
  }
  console.log('apiBaseUrl:' + baseUrl)
  service.defaults.baseURL = baseUrl


  console.log(to)
  /* has no token*/
  if (to.path == '/' && to.query.token) {
    // 免密登录
    await store.dispatch('user/setTokenLogin', {
      'token': to.query.token,
      'refresh_token': ''
    })
    store.dispatch("user/getUserInfo");
    let orgRes = await userDeptList();
    let deptList = orgRes.data;
    if (deptList.length === 1) {
      let dept = deptList[0];
      store.dispatch("user/setDeptInfo", dept.department[0]);
      if (dept.department[0].lng && dept.department[0].lat) {
        localStorage.setItem(
          "org_lat_lng",
          dept.department[0].lng + "," + dept.department[0].lat
        );
      } else {
        localStorage.setItem("org_lat_lng", "");

      }
      next(`/`)
    } else {
      next(`/orgList`)
    }
    // try {
    //   // get user info
    // } catch (error) {
    //   const response = error.response;
    //   next(`/login`)
    // }
  } else if (hasToken) {
    console.log('有token', hasToken)
    try {
      const hasUserId = store.getters.userId
      await store.dispatch('user/getUserInfo')
      // 网页token
      if (to.path === '/login') {
        console.log('to.login')
        // if is logged in, redirect to the home page
        next({
          path: '/'
        })
      } else if (to.path === '/sharedVideo') {
        console.log("to.sharedVideo");
        next()

      } else if (to.path === '/orgList') {
        console.log("to.orgList");
        next()

      } else if (to.path === '/') {
        console.log('to./', hasUserId)
        // if (!hasUserId) {
        //   try {
        //     await store.dispatch('user/getUserInfo')
        //   } catch (err) {
        //     const response = err.response;
        //     console.log(response)
        //     removeToken()
        //     next(`/login`)
        //     return
        //   }
        // }

        try {
          await store.dispatch("user/setAuth")
          next()
        } catch (err) {
          console.log("authErr", err);
          next(`/orgList`)
        }
      } else {
        console.log("to.else")
        try {
          await store.dispatch("user/setAuth")
          next()
        } catch (err) {
          console.log("authErr", err);
          next(`/orgList`)
        }
      }
    } catch (err) {
      Message.warning(err)
      store.dispatch("user/logout")
      next(`/login`)
    }
  } else {
    console.log("to.allEelse")
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // 过期时带上原来页面 重新登录后可返回
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
